<?php

namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Auth;

class AdminCheckLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $inputString    = $request->input('param');
        if (config('app.debug') == true && empty($inputString)) {
            session(['debug' => true],false);
            return $next($request);
        }
        session(['debug' => false],false);
        $token          = $request->server('HTTP_TOKEN');
        $timestamp      = $request->server('HTTP_TIMESTAMP');
        $request_from   = $request->server('HTTP_FROM');
        $ip             = $request->ip();
        //检测请求头
        if ($request_from !== 'admin') {
            return abort('444','Bad Request');
        }
        //检测时间戳
        if (empty($timestamp)) {
            return abort('444','Bad Request');
        }
        //判断时间戳是否为2分钟内的
        $diffInMinutes = Carbon::now()->diffInMinutes(Carbon::createFromTimestamp($timestamp));
        //如果超出2分钟 返回错误信息
        if($diffInMinutes >= 2) {
            return abort('444','Bad Request');
        }
        try {
            $decrypted = decrypt($token);
        } catch (DecryptException $e) {
            return abort('444','Bad Request');
        }
        if (empty($decrypted) || empty($decrypted['time']) || empty($decrypted['ip']) || empty($decrypted['name']) || empty($decrypted['password']) || empty($decrypted['api_token'])) {
            return abort('444','Bad Request');
        }
        if ($decrypted['time']-time() <= 0) {
            return abort('444','Bad Request');
        }
        if ($decrypted['ip'] !== $ip) {
            return abort('444','Bad Request');
        }
        $credentials                = [];
        $credentials['name']        = $decrypted['name'];
        $credentials['password']    = $decrypted['password'];
        if (!Auth::attempt($credentials)) {
            return abort('444','Bad Request');
        }
        $user = Auth::user();
        if ($user->api_token !== $decrypted['api_token']) {
            return abort('444','Bad Request');
        }
        $key            = md5(date('Ymd'));
        if (empty($inputString)) {
            return abort('444','Bad Request');
        }
        try {
            $after          = str_after($inputString,substr($key,0,16));
            $before         = str_before($after,substr($key,16,16));
            $input          = json_decode(base64_decode($before),true);
        } catch (\Exception $e) {
            return abort('444','Bad Request');
        }
        if (empty($input) || !is_array($input)) {
            return abort('444','Bad Request');
        }
        session(['admin_id' => $user->id]);
        $request->replace($input);
        return $next($request);
    }
}
